﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Super.DomainService;
using Super.Entities;
using Super.Infrastructure;
using Super.Common;
using Super.Mvc;

namespace Super.Web.Areas.Admin.Controllers
{
    public class PosController : BaseController
    {
        //
        // GET: /Admin/Pos/

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Order()
        {

            var id = Query.Get("id").ToInt(0);
            var adp = new DbContextAdapter();
            var posService = new PosService(adp);
            posService.SetSellItems(UserID, id);
            var sellList = posService.GetSellItems(UserID);

            decimal totalMoney = sellList.Sum(item => item.Count * item.Price);
            ViewBag.totalMoney = totalMoney;
            ViewBag.Count = sellList.Sum(item => item.Count);

            ViewBag.SetSellItems = sellList;
            return View();
        }

        public JsonResult SetBuyer()
        {
            var userId = Query.Post("userId").ToInt();
            if(userId>0)
            {
                var adp = new DbContextAdapter();
                var posService = new PosService(adp);
                posService.SetBuyUserId(UserID,userId);
            }

            return JsonBack.Tip(null);
        }

        public ActionResult Pay()
        {
            var adp = new DbContextAdapter();
            var posService = new PosService(adp);
            var sellList = posService.GetSellItems(UserID);
            var orderNo = posService.GetOrderNo(UserID);
            ViewBag.OrderNo = orderNo;
            decimal totalMoney = sellList.Sum(item => item.Count * item.Price);
            ViewBag.totalMoney = totalMoney;
            ViewBag.OrderTime = DateTime.Now;
            return View(sellList);
        }

        [HttpPost]
        public JsonResult Pay(int? z)
        {

            var orderTime = Query.Post("OrderTime").ToDateTime();
            if (!orderTime.HasValue)
            {
                return JsonBack.Tip("订单时间出现异常！");
            }
            var ShouldMoney = Query.Post("ShouldMoney").ToDecimal(0);
            var GetMoney = Query.Post("getMoney").ToDecimal(0);

            var adp = new DbContextAdapter();
            var posService = new PosService(adp);
            var stockchangeService = new StockChangeTypeService(adp);
            var orderDetailService = new BaseService<OrderDetail>(adp);
            var payService = new PayService(adp);
            var orderService = new OrderService(adp);
            var stockService = new StockService(adp);


            var sellList = posService.GetSellItems(UserID);
            var orderNo = posService.GetOrderNo(UserID);
            var totalMoney = sellList.Sum(a => a.Count * a.Price);
            var moneyChangeService = new MoneyChangeTypeService(adp);
            var moneyChange = moneyChangeService.GetStockChangeModel("零售",MoneyChangeTypeEnum.In);
            var stockChangeModel = stockchangeService.GetStockChangeModel("零售", StockChangeTypeEnum.Out);

            var userId = posService.GetBuyUserId(UserID);
            var OrderModel = new Order();
            OrderModel.CreateTime = orderTime.Value;
            OrderModel.TotalMoney = totalMoney;
            OrderModel.OrderNo = orderNo;
            OrderModel.RealMoney = ShouldMoney;
            OrderModel.LetMoney = totalMoney - ShouldMoney;
            OrderModel.GetMoney = GetMoney;
            OrderModel.StockChangeType_ID = stockChangeModel.ID;
            if(userId>0)
            {
                OrderModel.User_ID = userId;
                OrderModel.IsUser = true;
            }
            orderService.Repository.InsertOrUpdate(OrderModel);

            foreach (var item in sellList)
            {
                var orderDetailModel = new OrderDetail();
                orderDetailModel.Count = item.Count;
                orderDetailModel.Order_ID = OrderModel.ID;
                orderDetailModel.Price = item.Price;
                orderDetailModel.Stock_ID = item.StockId;
                orderDetailService.Repository.InsertOrUpdate(orderDetailModel);
            }

            var payModel = new PayRecord();
            payModel.TradeNo = Number.GetSerialNumber().ToString();
            payModel.CreateTime = DateTime.Now;
            payModel.Money = OrderModel.RealMoney;
            payModel.Subject = "零售收入";
            payModel.OrderNo = OrderModel.OrderNo;
            payModel.MoneyChangeType_ID = moneyChange.ID;
            payService.Repository.InsertOrUpdate(payModel);

            var stockIds = sellList.Select(a => a.StockId).ToList();
            var stockList = stockService.Repository.Find(a => stockIds.Contains(a.ID)).ToList();

            foreach (var stock in stockList)
            {
                if(stock.Count>0)
                {
                    stock.Count -= 1;
                    stockService.Repository.InsertOrUpdate(stock);
                }
            }
            adp.SaveChanges();
            if(adp.ErrorMessage==null)
            {
                posService.Clear(UserID);//更具销售人员ID，清空购物车
            }
            return JsonBack.Tip(adp.ErrorMessage, "posIndex");
        }

        public JsonResult Clear()
        {
            var orderNo = CacheService.GetOneCache(UserID.ToString());
            CacheService.SellStockCache.Remove(orderNo);
            CacheService.OneCache.Remove(UserID.ToString());
            return JsonBack.Tip(null, "posIndex");
        }

        public ActionResult Edit()
        {
            var id = Query.Get("id").ToInt(0);
            var adp = new DbContextAdapter();
            var posService = new PosService(adp);
            var sellList = posService.GetSellItems(UserID);
            var editItem = sellList.FirstOrDefault(a => a.StockId == id);
            return View(editItem);
        }

        [HttpPost]
        public JsonResult Edit(SellItems Model)
        {
            var id = Query.Post("ID").ToInt(0);
            var Count = Query.Post("Count").ToInt(0);

            var adp = new DbContextAdapter();
            var posService = new PosService(adp);

            if (id > 0)
            {
                posService.EditSellItems(UserID, id, Count);
            }
            return JsonBack.Tip(null, "posIndex");

        }

    }
}
